<template>
  <div class="box_container">
    <a-form
      :form="form"
      :label-col="{span: 2, offset: 0}"
      :wrapper-col="{span: 15, offset: 0}">
      <a-row>
        <a-col :span="8">
          <a-form-item
            label="请假类型"
            :label-col="{span: 6, offset: 0}"
            :wrapper-col="{span: 15}">
            <a-select
              v-decorator="['leave_type', formRules.leave_type ]"
              placeholder="请选择">
              <a-select-option
                v-for="item in leaveTypes"
                :key="item.item_val"
                :value="item.item_val">
                 <span
                   style="display: inline-block;width: 100%"
                   :title=" item.item_desc">
                    {{ item.item_desc }}
                 </span>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item
            label="开始时间"
            :label-col="{span: 6, offset: 0}"
            :wrapper-col="{span: 15}">
            <a-date-picker
              format="YYYY-MM-DD HH:mm"
              placeholder="请选择开始时间"
              v-decorator="['start_time', formRules.start_time]"
              :showTime="{ format: 'hh:mm', initialValue: moment('00:00', 'HH:mm'), minuteStep: 30, secondStep: 60 }"
              @change="startTimeChange">
            </a-date-picker>
          </a-form-item>
        </a-col>
        <a-col span="8">
          <a-form-item
            label="结束时间"
            :label-col="{span: 6, offset: 0}"
            :wrapper-col="{span: 15}">
            <a-date-picker
              format="YYYY-MM-DD HH:mm"
              v-decorator="['end_time', formRules.end_time]"
              :showTime="{ format: 'hh:mm', initialValue: moment('00:00', 'HH:mm'), minuteStep: 30, secondStep: 60  }"
              placeholder="请选择结束时间"
              @change="endTimeChange">
            </a-date-picker>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="总计时长"
            :label-col="{span: 6, offset: 0}"
            :wrapper-col="{span: 15}">
            <a-input
              type="number"
              v-decorator="['leave_days', formRules.leave_days]"
              placeholder="请输入总时长"
              step="0.1"
              @change="durationChange"
            ></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8" v-show="showAssign">
          <a-form-item
            label="审批人"
            :label-col="{span: 6, offset: 0}"
            :wrapper-col="{span: 15}">
            <a-select
              style="width: 100%"
              :disabled="approvalDisabled"
              v-decorator="['assignees', formRules.assignees]"
              placeholder="请选择"
              allowClear>
              <a-select-option
                v-for="(item, i) in assigneeList"
                :key="i"
                :value="item.username">{{item.realname}}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8" v-show="isGateway">
          <a-form-item
            label="下一审批人"
            :label-col="{span: 6, offset: 0}"
            :wrapper-col="{span: 15}">
            <a-alert  type="info" showIcon message="分支网关处不支持自定义选择下一审批人，将自动下发给所有可审批人。">，将发送给下一节点所有人</a-alert>
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item label="请假事由">
        <a-textarea
          v-decorator="['leave_reason', formRules.leave_reason]"
          placeholder="请输入内容,最多100字"
          :max-length = "maxLength"
          :rows="4"
        >
        </a-textarea>
      </a-form-item>
      <a-form-item label="说明附件">
        <div class="img_upload_container">
          <a-dropdown>
            <div class="upload-wrapper" @click="e => e.preventDefault()">
              <i class="el-icon-plus"></i>
              <span>上传照片</span>
            </div>
            <a-menu slot="overlay">
              <a-menu-item key="local">
                <a-upload
                  name="file"
                  v-decorator="['leave_enclosure', formRules.leave_enclosure]"
                  list-type="picture"
                  :action="uploadUrl"
                  :headers="{}"
                  :beforeUpload="beforeUpload"
                  @change="handleFileChange"
                  :showUploadList="showUploadList"
                  :data="{'biz':'temp'}">本地上传
                </a-upload>
              </a-menu-item>
              <a-menu-item style="display:none;" key="camera" @click="isCamera = true">拍照</a-menu-item>
            </a-menu>
          </a-dropdown>
          <ul class="img_upload_wrapper">
            <li v-for="(item, index) in listImgAll" :key="index">
              <img :src="imgMainUrl + item" alt="">
              <a-icon type="delete" @click="deleteImg(index)"/>
            </li>
          </ul>
        </div>
      </a-form-item>
      <a-form-item label="备注">
        <a-textarea
          v-decorator="['leave_comment', formRules.leave_comment]"
          placeholder="请输入内容,最多100字"
          :max-length = "maxLength"
          :rows="4"
        >
        </a-textarea>
      </a-form-item>
      <a-form-item class="form-item-bt-custom">
        <a-button @click="$emit('update:showChild', false)">关闭</a-button>
        <a-button type="primary" @click="handleSubmit('approve')">送批</a-button>
        <a-button style="display:none;" type="primary" @click="handleSubmit('save')">保存</a-button>
      </a-form-item>
    </a-form>
    <camera-box
      v-if="isCamera"
      :is-camera.sync="isCamera"
      :list-img-all.sync="listImgAll"></camera-box>
  </div>
</template>

<script>
import { CameraBox } from '@/myComponents'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { imgMainUrl } from '@/config/leave.config'
import api from '@/api/apiUrl'
import { getHours } from '@/utils/CalculateDuration'
import {getAction} from "@/api/process";

export default {
  name: 'AddLeaveListing',
  components: {
    CameraBox
  },
  props: {
    openType: {
      type: Number,
      default: 0
    },
    detailInfo: {
      type: Object,
      default: () => {}
    },
    showChild: {
      type: Boolean,
      default: false
    },
    identity: {
      type: String,
      default: ''
    }
  },
  computed: {
    leaveTypes () {
      return this.$store.getters.leaveTypes
    },
    userInfo () {
      return this.$store.getters.userInfo
    },
    depInfo () {
      return this.$store.getters.depInfo
    }
  },
  data () {
    return {
      approvalDisabled: false,
      maxLength: 100,
      showAssign: false,
      isGateway: false,
      assigneeList: [],
      imgMainUrl,
      showUploadList: false,
      uploadUrl: '/process-api' + api.Process.uploadImg,
      form: this.$form.createForm(this, {}),
      isCamera: false,
      isLocal: false,
      listImgAll: [],
      formRules: {
        leave_type: {
          rules: [{ required: true, message: '请选择请假类型' }]
        },
        assignees: {
          rules: [{ required: true, message: '请选择审批人' }]
        },
        start_time: {
          rules: [
            { required: true, message: '请输入开始时间'}]
        },
        end_time: {
          rules: [
            { required: true, message: '请输入结束时间'}
          ]
        },
        leave_days: {
          rules: [{ required: true, message: '请输入请假时长' }]
        },
        leave_reason: {
          rules: [{ required: false, message: '请输入请假事由', trigger: 'blur' }]
        },
        leave_enclosure: {
          rules: [{ required: false, message: '请选择附件'}]
        },
        leave_comment: {
          rules: [{ required: false, message: '请输入备注内容'}]
        }
      },
      formData: {
        leave_type: '',
        start_time: null,
        end_time: null,
        leave_days: 0,
        leave_reason: '',
        leave_enclosure: '',
        procDefId: '',
        procDeTitle: '',
        leave_comment: '',
        sendMessage: true,
        tableName: 'leave_detail_form',
        filedNames: 'leave_type,start_time,end_time,leave_days,leave_reason,leave_enclosure,leave_comment'
      },
      processList: [
        {
          id: 0,
          procDefId: 'withinThreeDays:1:35012',
          text: '请假三天内',
          procDeTitle: 'withinThreeDays'
        },
        {
          id: 1,
          procDefId: 'threeDaysOrLessThanAWeek:1:35008',
          text: '请假三天以上一周内',
          procDeTitle: 'threeDaysOrLessThanAWeek'
        },
        {
          id: 2,
          procDefId: 'moreThanAWeek:1:35004',
          text: '请假一周以上',
          procDeTitle: 'moreThanAWeek'
        },
        {
          id: 3,
          procDefId: 'DirectToTopManager:1:75371',
          text: '部门经理请假',
          procDeTitle: 'DirectToTopManager'
        },
        {
          id: 4,
          procDefId: 'DirectToDepartmentUnderAWeek:3:75356',
          text: '直接部门经理审核(7天以内)',
          procDeTitle: 'DirectToDepartmentUnderAWeek'
        },
        {
          id: 5,
          procDefId: 'DirectToDepartmentMoreAWeek:1:75360',
          text: '直接部门经理审核(大于等于7天)',
          procDeTitle: 'DirectToDepartmentMoreAWeek'
        }
      ],
      url: {
        getFirstNode:'/actProcessIns/getFirstNode'
      },
      leaveParams: {
        id: '',
        priority: 0,
        firstGateWay: false,
        procDefId: '',
        title: '',
        sendMessage: true,
        assignees: ''
      },
      error: ''
    }
  },
  watch: {
    listImgAll: {
      handler: function (n, o) {
        console.log('watch---listImgAll', n)
        this.form.setFieldsValue({
          'leave_enclosure': n.join(',')
        })
      },
      deep: true
    },
    'formData.leave_days': {
      handler: function (n, o) {
        if (n && n != o) {
        this.calculateDuration(n)
        } else if (!n) {
          this.showAssign = false
          this.isGateway = false
          this.formData.procDefId = ''
          this.formData.procDeTitle = ''
          this.leaveParams.procDefId = ''
          this.leaveParams.title = ''
        }
      }
    }
  },
  created () {
    console.log('userInfo', this.userInfo)
    if (this.openType === 1) {
      this.formData = Object.assign(this.formData, this.detailInfo)
      console.log('detail---editapply', this.formData)
    }
  },
  mounted () {
    if (this.openType === 1) {
      this.form.setFieldsValue({
        leave_type: this.formData.leave_type,
        start_time: this.moment(new Date(this.formData.start_time), 'YYYY-MM-DD HH:mm'),
        end_time: this.moment(new Date(this.formData.end_time), 'YYYY-MM-DD HH:mm'),
        leave_days: this.formData.leave_days,
        leave_reason: this.formData.leave_reason,
        leave_enclosure: this.formData.leave_enclosure,
        leave_comment: this.formData.leave_comment
      })
      if (this.formData.leave_enclosure === '') {
        this.listImgAll = []
      } else {
        this.listImgAll = this.formData.leave_enclosure.split(',')
      }
    }
  },
  methods: {
    durationChange (e) {
      console.log(e.target.value)
      const _duration = e.target.value || 0
      if (_duration) {
        this.calculateDuration(_duration)
      } else {
        this.showAssign = false
        this.isGateway = false
        this.formData.procDefId = ''
        this.formData.procDeTitle = ''
        this.leaveParams.procDefId = ''
        this.leaveParams.title = ''
      }
    },
    calculateDuration (n) {
      const days = Number(n) / 8
      if (this.identity === 'type_leader') { // 部门经理请假
        this.formData.procDefId = this.processList[3].procDefId
        this.formData.procDeTitle = this.processList[3].procDeTitle
      }
      if (this.identity === 'type_other') { // 直属经理审批
        if (days < 7) {
          this.formData.procDefId = this.processList[4].procDefId
          this.formData.procDeTitle = this.processList[4].procDeTitle
        } else if (days >= 7) {
          this.formData.procDefId = this.processList[5].procDefId
          this.formData.procDeTitle = this.processList[5].procDeTitle
        }
      }
      if (this.identity === 'type_developer') { // 项目经理审批
        if (days < 3) {
          this.formData.procDefId = this.processList[0].procDefId
          this.formData.procDeTitle = this.processList[0].procDeTitle
        }
        if (days >= 3 && days < 7) {
          this.formData.procDefId = this.processList[1].procDefId
          this.formData.procDeTitle = this.processList[1].procDeTitle
        }
        if (days >= 7) {
          this.formData.procDefId = this.processList[2].procDefId
          this.formData.procDeTitle = this.processList[2].procDeTitle
        }
      }
      this.leaveParams.procDefId = this.formData.procDefId
      this.leaveParams.title = this.formData.procDeTitle
      this.getApproveMan(this.formData.procDefId)
    },
    startTimeChange (value) {
      console.log('startTimeChange-startTimeChange--1', value)
      if (value) {
        let startTime = ''
        if (value.minutes() != 0 && value.minutes() != 30) {
          startTime = value.minutes(0).format('YYYY-MM-DD HH:mm')
        }
        startTime = value.format('YYYY-MM-DD HH:mm')
        this.formData.start_time = startTime
        console.log('startTimeChange-startTimeChange--2', this.formData.start_time, this.formData.end_time)
        if (this.formData.start_time && this.formData.end_time) {
          const duration = getHours(this.formData.start_time, this.formData.end_time)
          this.formData.leave_days = Number(duration).toFixed(2)
          this.form.setFieldsValue({
            leave_days: Number(duration).toFixed(2)
          })
        } else {
          this.formData.leave_days = ''
        }
      }
    },
    endTimeChange (value) {
      console.log('endTimeChange-endTimeChange--1', value)
      if (value) {
        let endTime = ''
        if (value.minutes() != 0 && value.minutes() != 30) {
          endTime = value.minutes(0).format('YYYY-MM-DD HH:mm')
        }
        endTime = value.format('YYYY-MM-DD HH:mm')
        const startTime = this.formData.start_time
        this.formData.end_time = endTime
        if (new Date(endTime).getTime() < (new Date(startTime).getTime())) {
          this.formData.end_time = ''
          this.$message.warning('结束时间不能晚于开始时间')
        } else {
          console.log('endTimeChange-endTimeChange--2', this.formData.start_time, this.formData.end_time)
          if (this.formData.start_time && this.formData.end_time) {
            const duration = getHours(this.formData.start_time, this.formData.end_time)
            this.formData.leave_days = Number(duration).toFixed(2)
            this.form.setFieldsValue({
              leave_days: Number(duration).toFixed(2)
            })
          } else {
            this.formData.leave_days = ''
          }
        }
      }
    },
    getApproveMan (procDefId) {
      getAction(this.url.getFirstNode,{procDefId, loginUserId: this.userInfo.id}).then(res => {
        if (res.success) {
          if (res.result.type == 3 || res.result.type == 4) {
            this.isGateway = true;
            this.leaveParams.firstGateway = true;
            this.showAssign = false;
            this.error = "";
            return;
          }
          this.leaveParams.firstGateway = false;
          this.isGateway = false
          if (res.result.users && res.result.users.length > 0) {
            this.error = ''
            let list =  res.result.users
            if (this.identity == 'type_other') {
              for (let i = 0; i < list.length; i++) {
                let depId = this.depInfo.superiorDepId == '0' ? this.depInfo.id : this.depInfo.superiorDepId
                console.log('depId', depId)
                console.log('depId-', list[i]['departIds'])
                if (depId == list[i]['departIds']) {
                  this.assigneeList.push(list[i])
                }
              }
              this.approvalDisabled = true
            } else {
              this.assigneeList = list
            }
            this.leaveParams.assignees = this.assigneeList[0]['username']
            this.showAssign = true;
            this.form.setFieldsValue({
              assignees: this.assigneeList[0]['username']
            })
          } else {
            this.leaveParams.assignees = ''
            this.showAssign = true;
            this.error = '审批节点未分配候选审批人员，请联系管理员！';
          }
          if (this.error){
            this.$message.error(this.error)
            return;
          }
        } else {
          this.$message.error(res.message)
        }
      })
    },
    moment,
    handleSubmit (type) {
      this.form.validateFields((err, values) => {
        console.log('values11', values)
        if (!err) {
          this.formData.leave_type = values.leave_type
          this.formData.leave_days = values.leave_days
          this.formData.leave_reason = values.leave_reason || ''
          this.formData.leave_enclosure = this.listImgAll.join(',')
          this.formData.leave_comment = values.leave_comment || ''
          this.leaveParams.assignees = values.assignees
          // this.$emit('update:showChild', false)
          // this.$emit('update:identity', '')
          this.$emit('handleForm', this.openType, this.formData, this.leaveParams, type)
        }
      })
    },
    deleteImg (index) {
      this.listImgAll.splice(index, 1)
    },
    handleFileChange (info) {
      // console.log('info', info)
      if (info.file.response) {
        if (this.listImgAll.length >= 3) {
          this.$message.info('最多上传3张图片')
        } else {
          this.listImgAll.push(info.file.response.message)
        }
      }
     // console.log('handleFileChange', this.listImgAll)
    },
    beforeUpload (info) {
      if (info.type.indexOf('image') > -1) {
        return true;
      } else {
        this.$message.error('请上传图片类型的文件');
        return false;
      }
    }
  }
}
</script>

<style scoped lang="less">
.img_upload_container {
  display: flex;
  flex-wrap: nowrap;
  width: 500px;
  height: 120px;
}
.upload-wrapper {
  display: flex;
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  box-sizing: border-box;
  width: 108px;
  height: 108px;
  cursor: pointer;
  line-height: 108px;
  text-align: center;
  font-size: 28px;
  font-weight: 900;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  span {
    display: inline-block;
    margin-top: 5px;
    line-height: 0;
    font-size: 12px;
    font-weight: 300;
  }
  &:hover {
    border: 1px dashed #389FFD;
  }
}
.img_upload_wrapper {
  list-style:none;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  li {
    position: relative;
    width: 104px;
    height: 104px;
    background: #FFFFFF;
    border-radius: 4px;
    border: 1px solid #E2E7F2;
    margin-right: 10px;
    img {
      width: 88px;
      height: 88px;
      margin-left: 8px;
      margin-top: 8px;
    }
    i {
      position: absolute;
      right: 13px;
      top: 13px;
    }
  }
}
</style>
